import { _decorator, Component, Node, Toggle, ScrollView, EventTouch, Animation, Label, Sprite, ImageAsset, SpriteFrame, Prefab, Input } from 'cc';
import { DataManager } from '../Public/DataManager';
import { PoolManager } from '../Public/PoolManager';
import { PublicFn } from '../Public/PublicFn';
const { ccclass, property } = _decorator;

@ccclass('Atlas')
export class Atlas extends Component {
    /**节点切换数组 */
    @property({ type: [Node], displayName: '节点切换数组' })
    ChangeNodeArr: Node[] = [];
    /**滚动节点 */
    @property({ type: ScrollView, displayName: '滚动节点' })
    scrollView: ScrollView = null;
    /**选择页面 */
    @property({ type: Node, displayName: '选择页面' })
    SelectPage: Node = null;
    /**兑换页面 */
    @property({ type: Node, displayName: '兑换页面' })
    ExchangePage: Node = null;
    /**合成页面 */
    @property({ type: Node, displayName: '合成页面' })
    ComposePage: Node = null;
    /**合成成功 */
    @property({ type: Node, displayName: '合成成功' })
    ComposeSucc: Node = null;
    /**解锁 */
    @property({ type: Node, displayName: '解锁' })
    lock: Node = null;
    @property(Node)
    bagList: Node = null;
    @property(Node)
    CollectionContent: Node = null;
    @property(Prefab)
    bagPrefab: Prefab = null;
    is_compound: number = 0;
    is_compound_details: number = 0;
    is_exchange: number = 0;
    exchange_id: string = ``;
    CollectionArr: any[] = [];
    collectionIndex: number = 0;
    start() {
        this.getBagList();
        this.getCollectionList();
    }

    update(deltaTime: number) {

    }
    /**返回主页 */
    BacktoMain() {
        this.node.setPosition(600, 0);
    }
    /**更改功能页面 */
    ChangePage(toggle: Toggle) {
        this.ChangeNodeArr.forEach((e)=>
        {
            e.active = false;
        })
        const node = this.ChangeNodeArr[toggle.node.getSiblingIndex()];
        node.active = true;
        this.scrollView.content = node;
    }
    /**打开合成页面 */
    OpenSelectPage(e: EventTouch) {
        // this.SelectPage.active = true;
        const Item: any = DataManager.Instance.bagList[e.target.getSiblingIndex()];
        if (!Item) {
            return;
        }
        this.is_compound = Item.prop.is_compound
        this.is_compound_details = Item.prop.is_compound_details
        this.is_exchange = Item.prop.is_exchange
        if (this.is_exchange) {
            // this.ExchangePage.getChildByPath(`content/name`).getComponent(Label).string = Item.prop.prop_name;
            // this.ExchangePage.getChildByPath(`content/text`).getComponent(Label).string = Item.prop.describe;
            PublicFn.Instance.changeUrlImg(Item.prop.prop_img, this.ExchangePage.getChildByPath(`content/pic`).getComponent(Sprite));
            this.ExchangeList(Item.prop_id, this.ExchangePage.getChildByPath(`content/name`).getComponent(Label), this.ExchangePage.getChildByPath(`content/text`).getComponent(Label));
            this.OpenExchangePage();
        }
        else if (this.is_compound) {
            this.ComposePage.getChildByPath(`content/name`).getComponent(Label).string = Item.prop.prop_name;
            this.ComposePage.getChildByPath(`content/text`).getComponent(Label).string = Item.prop.describe;
            PublicFn.Instance.changeUrlImg(Item.prop.prop_img, this.ComposePage.getChildByPath(`content/icon`).getComponent(Sprite));
            this.getcompoundList(Item.prop_id, this.ComposePage.getChildByPath(`content/pic`).getComponent(Sprite), this.ComposePage.getChildByPath(`content/num`).getComponent(Label));
            this.OpenComposePage();

        }

    }
    /**打开合成页面 */
    OpenComposePage() {
        this.SelectPage.active = false;
        this.ComposePage.active = true;
    }
    /**打开兑换页面 */
    OpenExchangePage() {
        this.SelectPage.active = false;
        this.ExchangePage.active = true;
    }

    /**关闭切换数组中的某个节点 */
    ClosePage(e: EventTouch, str: string) {
        const index = Number(str);
        this.ChangeNodeArr[index].active = false;
    }
    /**进行合成 */
    ActiveCompose() {
        let xhr = new XMLHttpRequest();
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/compound`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
        xhr.send(`compound_id=${DataManager.Instance.compound_id}`);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { code, data } = JSON.parse(xhr.response)
                if (code == 200) {
                    console.log('data :>> ', data);
                    this.ComposePage.active = false;
                    this.ComposeSucc.active = true;
                    this.ComposeSucc.getChildByPath('content/name').getComponent(Label).string = `${DataManager.Instance.compound_name}`;
                    PublicFn.Instance.changeUrlImg(DataManager.Instance.compound_img, this.ComposeSucc.getChildByPath('content/pic').getComponent(Sprite));
                    this.ComposeSucc.getComponentInChildren(Animation).play();
                    this.getBagList();
                }
                else {
                    console.log('JSON.parse(xhr.response) :>> ', JSON.parse(xhr.response));
                }
            }
        }

    }
    /**进行兑换 */
    ActiveExchange() {
        let xhr = new XMLHttpRequest();
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/exchange`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
        xhr.send(`address_id=441878579022659584&exchange_id=${this.exchange_id}`);
        console.log('this.exchange_id :>> ', this.exchange_id);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { code, data } = JSON.parse(xhr.response)
                if (code == 200) {
                    console.log('data :>> ', data);
                    this.ExchangePage.active = false;
                    this.getBagList();
                }
                else {
                    console.log('JSON.parse(xhr.response) :>> ', JSON.parse(xhr.response));
                }
            }
        }
    }
    /**背包图鉴互相切换 */
    BagOrAtlas(toggle: Toggle) {
        this.ChangeNodeArr[4].active = false;
        this.ChangeNodeArr[5].active = false;
        this.ChangeNodeArr[Number(toggle.node.name)].active = true;
    }
    /**生成背包列表 */
    getBagList() {
        let xhr = new XMLHttpRequest();
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/bagSelect`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
        xhr.send(``);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { code, data } = JSON.parse(xhr.response)
                if (code == 200) {
                    console.log('data :>> ', data);
                    DataManager.Instance.bagList = data[0].detailsList;
                    this.bagList.children.forEach((e) => {
                        e.getComponentInChildren(Sprite).spriteFrame = null;
                        e.getComponentInChildren(Label).string = ``;
                    })
                    data[0].detailsList.forEach((e, i) => {
                        if (i > 14) {
                            PoolManager.Instance.getNode(this.bagPrefab, this.bagList, 'bag');
                        }
                        this.bagList.children[i].getComponentInChildren(Label).string = `X${e.num}`;
                        PublicFn.Instance.changeUrlImg(e.prop.prop_img, this.bagList.children[i].getComponentInChildren(Sprite));
                    })
                }
            }
        }
    }
    /**生成合成列表 */
    getcompoundList(id: string, sprite: Sprite, num: Label) {
        let xhr = new XMLHttpRequest();
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/compoundList`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
        xhr.send(`prop_id=${id}`);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { code, data } = JSON.parse(xhr.response)
                if (code == 200) {
                    console.log('data :>> ', data);
                    PublicFn.Instance.changeUrlImg(data.Compound[0].compound_img, sprite);
                    num.string = `X${data.CompoundDetails[0].count}`;
                    DataManager.Instance.compound_id = data.Compound[0].compound_id
                    DataManager.Instance.compound_name = data.Compound[0].compound_name
                    DataManager.Instance.compound_img = data.Compound[0].compound_img
                }
            }
        }
    }
    /**图鉴列表 */
    getCollectionList() {
        let xhr = new XMLHttpRequest();
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/collectionSelect`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
        xhr.send(`game_user_id=${DataManager.Instance.game_user_id}`);
        // console.log('DataManager.Instance.game_user_id', DataManager.Instance.game_user_id)
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { code, data } = JSON.parse(xhr.response)
                if (code == 200) {
                    console.log('data :>> ', data);
                    for (const key in data) {
                        this.CollectionArr = data[key].subclass;
                        const parent = this.CollectionContent;
                        const len = parent.children.length;
                        parent.children.forEach((e) => {
                            e.off(Input.EventType.TOUCH_END, this.OpenLock, this);
                        })
                        this.CollectionArr.forEach((e, i) => {
                            if (i > len) {
                                PoolManager.Instance.getNode(this.bagPrefab, parent, 'c');
                            }
                            PublicFn.Instance.changeUrlImg(e.collection_img, parent.children[i].children[0].getComponent(Sprite))
                            if (e.type == 1) {
                                parent.children[i].children[1].active = true;
                            }
                            else {
                                parent.children[i].children[1].active = false;
                            }
                        })
                        parent.children.forEach((e) => {
                            e.on(Input.EventType.TOUCH_END, this.OpenLock, this);
                        })
                    }
                }
                else {
                    console.log('JSON.parse(xhr.response) :>> ', JSON.parse(xhr.response));
                }
            }
        }
    }
    /**查询配方 */
    getItemList(id: string) {
        let xhr = new XMLHttpRequest();
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/compoundGet`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
        xhr.send(`compound_id=${id}`);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { code, data } = JSON.parse(xhr.response)
                if (code == 200) {
                    console.log('data :>> ', data);
                }
                else {
                    console.log('JSON.parse(xhr.response) :>> ', JSON.parse(xhr.response));
                }
            }
        }
    }
    /**兑换列表 */
    ExchangeList(id: string, lname: Label, ltext: Label) {
        let xhr = new XMLHttpRequest();
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/exchangeList`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
        xhr.send(`prop_id=${id}`);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { code, data } = JSON.parse(xhr.response)
                if (code == 200) {
                    console.log('data :>> ', data);
                    lname.string = `${data.data[0].exchange_name}`;
                    ltext.string = `${data.data[0].exchange_describe}`;
                    this.exchange_id = data.data[0].exchange_id;
                }
                else {
                    console.log('JSON.parse(xhr.response) :>> ', JSON.parse(xhr.response));
                }
            }
        }

    }
    OpenLock(e: EventTouch) {
        this.collectionIndex = e.target.getSiblingIndex();
        const mes = this.CollectionArr[this.collectionIndex];
        if (mes) {
            if (mes.type != 1) {

                return;
            }
            PublicFn.Instance.changeUrlImg(mes.collection_img, this.lock.getChildByPath('content/pic').getComponent(Sprite));
            this.lock.getChildByPath('content/text').getComponent(Label).string = mes.collection_name;
            this.lock.active = true;
        }
        // else
        // {
        //     PublicFn.Instance.changeImg('imgs/未获得背景',this.lock.getChildByPath('content/pic').getComponent(Sprite))
        //     this.lock.getChildByPath('content/text').getComponent(Label).string='未知';
        // }

    }
    CloseLock() {
        this.lock.active = false;
    }
    /**解锁 */
    ActiveLock() {
        const mes = this.CollectionArr[this.collectionIndex];

        if (mes) {
            let xhr = new XMLHttpRequest()
            xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/stageClear`);
            xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
            xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
            xhr.send(`collection_id=${mes.collection_id}`);
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    const { code, data } = JSON.parse(xhr.response)
                    if (code == 200) {
                        console.log('data :>> ', data);
                        console.log('data :>> ', data.msg);
                        this.CloseLock();
                        this.getCollectionList();
                    }
                    else {
                        console.log('JSON.parse(xhr.response) :>> ', JSON.parse(xhr.response));
                    }
                }
            }
        }
    }
}

